package org.xuyuji.web.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.xuyuji.web.data.UserData;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private String loginUrl;
	
	private String contextPath;
       
    public LoginServlet() {
    	
    }
    
    @Override
    public void init(ServletConfig config) throws ServletException {
    	contextPath = config.getServletContext().getContextPath();
    	loginUrl = config.getInitParameter("loginPage");
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher(loginUrl).forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		if(UserData.findUser(username, password) != null){
			System.out.println("login success,username:" + username + ",password:" + password);
			response.sendRedirect(contextPath + "/pages/index.jsp");
		}else{
			System.out.println("login fail,username:" + username + ",password:" + password);
			request.getRequestDispatcher(loginUrl).forward(request, response);
		}
		
	}

}
